import { bindData, ifPlayerData, getData } from "../Data/dataBase";
import { playerExpData } from "../configData/playerExpData";
import panelBase from "../base/panelBase";
import { GlobalFunction } from "../base/GlobalFunction";


const { ccclass, property } = cc._decorator;

@ccclass
export default class playerInfoBox extends panelBase {

    @property(cc.Sprite)
    CharacterSpNode: cc.Node = null;
    @property(cc.Label)
    levelLabel: cc.Label = null;
    @property(cc.Label)
    healthLabel: cc.Label = null;
    @property(cc.Label)
    expLabel: cc.Label = null;

    private _hp: number = 0;
    private _level: number = 0;
    private _maxHp: number = 0;
    private _exp : number = 0;

    onLoad() {
        bindData("PLAYER_DATA", "", this.initData.bind(this), this);
        bindData("PLAYER_DATA", "HP", this.onHpChange.bind(this), this);
        bindData("PLAYER_DATA", "LEVEL", this.onLevelChange.bind(this), this);
        bindData("PLAYER_DATA", "MAX_HP", this.onMaxHpChange.bind(this), this);
        bindData("PLAYER_DATA", "EXP", this.onExpChange.bind(this), this);
        this.initData(getData("PLAYER_DATA"));
        this.CharacterSpNode.getComponent("copyTexture").setTarget(GlobalFunction.getWorldMgr().getPlayer());
    }

    initData(data: ifPlayerData) {
        this._hp = data.hp;
        this._level = data.level;
        this._maxHp = data.maxHp;
        this._exp = data.exp;
        this.refreshHpLabel();
        this.refreshLevel();
        this.refreshExpLabel();
    }

    refreshHpLabel() {
        this.healthLabel.string = this._hp + "/" + this._maxHp;
    }

    refreshLevel() {
        this.levelLabel.string = this._level.toString();
        var tween = new cc.Tween();
        tween.target(this.levelLabel.node)
            .to(0.1, { scale: 2.0, opacity: 200 }, null)
            .to(0.1, { scale: 1.0, opacity: 255 }, null)
            .start();
    }

    refreshExpLabel(){
        var preNeedExp = playerExpData[this._level - 1] != null ? playerExpData[this._level - 1] : 0;
        var nextNeedExp = playerExpData[this._level] != null ? playerExpData[this._level] : 0;
        this.expLabel.string = (this._exp - preNeedExp) + "/" + (nextNeedExp - preNeedExp);
    }

    onHpChange(hp:number){
        this._hp = hp;
        this.refreshHpLabel();
    }
    onMaxHpChange(maxHp:number){
        this._maxHp = maxHp;
        this.refreshHpLabel();
    }
    onLevelChange(level:number){
        this._level = level;
        this.refreshLevel();
        this.refreshExpLabel();
    }
    onExpChange(exp:number){
        this._exp = exp;
        this.refreshExpLabel();
    }

    onClickClose()
    {
        this.close();
    }

}
